﻿using System;
using System.Text;
using System.Text.RegularExpressions;

namespace DotNetConverter
{
    public static class Reader
    {
        public static string VBToCSharp(string VBCode)
        {
            int pos = 0;
            StringBuilder cSharp = new StringBuilder();

            while (pos < VBCode.Length)
            {
                string word = GetWord(VBCode, ref pos);
                //string line = "";

                switch (word)
                { 
                    case "Imports":

                        cSharp.AppendFormat("using {0};\r\n", ReadToEndOfLine(VBCode, ref pos));
                        break;

                    case "Option":

                        ReadToEndOfLine(VBCode, ref pos);
                        break;

                    case "Friend":
                    case "Private":
                    case "Protected":
                    case "Protected Friend":
                    case "Public":

                        cSharp.AppendFormat("{0} ", word.ToLower());
                        break;

                    case "Class":

                        cSharp.AppendFormat("class ");
                        break;

                    default:

                        cSharp.AppendFormat("{0} ", word);
                        break;
                }
            }

            return cSharp.ToString();
        }

        private static string GetWord(string VBCode, ref int pos)
        {
            Match word = Regex.Match(VBCode.Substring(pos), @"\w+");
            pos += word.Index + word.Length;

            string wordVal = word.Value;

            if (wordVal == "Protected" && Regex.IsMatch(VBCode.Substring(pos), @"\s*Friend(?=\s)"))
                wordVal += GetWord(VBCode, ref pos);

            return word.Value;
        }

        private static string ReadToEndOfLine(string VBCode, ref int pos)
        {
            Match line = Regex.Match(VBCode.Substring(pos), @"[^\r]+");
            pos += line.Index + line.Length;
            return line.Value;
        }
    }
}
